<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	
</body>
<script>
/*遵循LIFO原则*/
function Stack(){
	this.items=[];
	this.push=function(element){
		this.items.push(element);
	};
	this.pop=function(){
		return this.items.pop();
	};
	this.peek=function(){
		return this.items[this.items.length-1];
	};
	this.isEmpty=function(){
		return this.items.length==0;
	};
	this.size=function(){
		return this.items.length;
	};
	this.clear=function(){
		this.items=[];
	};
	this.print=function(){
		console.log(this.items.toString());
	}
}
//应用：十进制转化二进制
//规则：将10进制的数字和2整除（二进制是满2仅1），直到结果是0为止，
function divideBy2(decNumber){
	var remStack=new Stack(),
		rem,
		binaryString='';
	while(decNumber>0){
		rem=Math.floor(decNumber%2);
		remStack.push(rem);
		decNumber=Math.floor(decNumber/2);
	}
	while(!remStack.isEmpty()){
		binaryString += remStack.pop().toString();
	}

	return binaryString;
}

//规则：将十进制转化成二进制，余数是0或1，将十进制转化为八进制，余数是0-7之间的数，将十进制转化为16进制，余数是0-9之间的数字加上ABCDEF（对应11，12，13，14，15）
function baseConverter(decNumber,base){
	var remStack=new Stack(),
	rem,
	baseString='',
	digits='0123456789ABCDEF';

	while(decNumber>0){
		rem=Math.floor(decNumber % base);
		remStack.push(rem);
		decNumber=Math.floor(decNumber / base);
	}

	while(!remStack.isEmpty()){
		baseString += digits[remStack.pop()]; 
	}

	return baseString;
}

//测试
console.log(baseConverter(100345,2));
console.log(baseConverter(100345,8));
console.log(baseConverter(100345,16));
</script>
</html>